const app = getApp();
let playheartbeatInterval = null;

const liveroom = require('../../utils/liveroom.js');
const webimhandler = require('../../utils/webim_handler');
const getlogininfo = require('../../getlogininfo');
import { getUserInfo } from '../../../common/utils/ws/wsxcx-opendata-sdk';
const device = wx.getSystemInfoSync();

Page({
  data: {
    playing: true,
    videoContext: {},
    fullScreen: false,
    playUrl: '',
    orientation: 'vertical',
    objectFit: 'fillCrop',
    muted: false,
    backgroundMuted: false,
    debug: false,
    headerHeight: app.globalData.headerHeight,
    statusBarHeight: app.globalData.statusBarHeight,
    autoplay: true,
    isSucess: true,
    mode: 'HD', // SD(标清) HD(高清)
    inputMsg: '',
    showComment: false,
    comment: [],
    supportChat: false,
    audienceCount: 0,
    isGetLoginInfo: false,
    tip: '',
    tipAnimation: {},
  },
  tips: [],
  tipInterval: null,
  isChatSupport() {
    return new Promise((resolve, reject) => {
      app.util.request({
        url: 'entry/wxapp/index',
        data: {
          op: 'is_chat',
        },
        module: 'cm_lvb',
        success: (res) => {
          resolve(res.data && res.data.data && res.data.data.is_chat == 1);
        },
        fail: () => {
          resolve(false);
        },
      });
    });
  },
  onScanQR: function () {
    this.stop();
    this.createContext();
    let self = this;
    wx.scanCode({
      onlyFromCamera: true,
      success: (res) => {
        console.log(res);
        self.setData({
          playUrl: res.result,
        });
      },
    });
  },
  onPlayClick: function() {
    let url = this.data.playUrl;
    if (url.indexOf('rtmp:') == 0) { } else if (url.indexOf('https:') == 0 || url.indexOf('http:') == 0) {
      if (url.indexOf('.flv') != -1) { }
    } else {
      wx.showToast({
        title: '播放地址不合法，目前仅支持rtmp,flv方式!',
        icon: 'none',
      });
    }

    this.setData({
      playing: !this.data.playing,
    });

    if (this.data.playing) {
      this.data.videoContext.play();
      console.log('video play()');
      wx.showLoading({
        title: '',
      });
    } else {
      this.data.videoContext.stop();
      console.log('video stop()');
      wx.hideLoading();
    }
  },

  onOrientationClick: function() {
    if (this.data.orientation == 'vertical') {
      this.data.orientation = 'horizontal';
    } else {
      this.data.orientation = 'vertical';
    }

    this.setData({
      orientation: this.data.orientation,
    });
  },

  onObjectfitClick: function() {
    if (this.data.objectFit == 'fillCrop') {
      this.data.objectFit = 'contain';
    } else {
      this.data.objectFit = 'fillCrop';
    }

    this.setData({
      objectFit: this.data.objectFit,
    });
  },
  checkDebug() {
    app.util.request({
      url: 'entry/wxapp/index',
      data: {
        op: 'checkSwitch',
      },
      module: 'cm_lvb',
      success: res => {
        if (res.data && res.data.errno == 0) {
          const data = res.data.data;
          if (data) {
            this.setData({ debug: data.is_debug == 1 });
          }
        }
      },
    });
  },
  onLogClick: function() {
    this.setData({
      debug: !this.data.debug,
    });
    let that = this;
    setTimeout(() => {
      that.setData({
        exterFlag: !that.data.exterFlag,
      });
    }, 10);
  },

  onMuteClick: function() {
    this.setData({
      muted: !this.data.muted,
    });
  },

  onFullScreenClick: function () {
    if (!this.data.fullScreen) {
      this.data.videoContext.requestFullScreen({
        direction: 0,
      });
    } else {
      this.data.videoContext.exitFullScreen({});
    }
  },

  onPlayEvent: function(e) {
    console.log('e.detail.code', e.detail.code);
    if (e.detail.code === -2301 || e.detail.code === 2006) {
      this.stop();
      this.setData({
        isSucess: false,
      });
    }
    if (e.detail.code == 2004) {
      wx.hideLoading();
    }
  },

  onFullScreenChange: function (e) {
    this.setData({
      fullScreen: e.detail.fullScreen,
    });
    console.log(e);
    wx.showToast({
      title: this.data.fullScreen ? '全屏' : '退出全屏',
    });
  },

  stop: function() {
    this.setData({
      playing: false,
      // playUrl: "rtmp://2157.liveplay.myqcloud.com/live/2157_wx_live_test1",
      orientation: 'vertical',
      objectFit: 'contain',
      muted: false,
      fullScreen: false,
      backgroundMuted: false,
      debug: false,
      exterFlag: false,
    });
    this.data.videoContext.stop();
    if (this.data.supportChat) {
    webimhandler.quitBigGroup();
    }
    wx.hideLoading();
  },

  createContext: function() {
    let context = wx.createCanvasContext('audience-comment', this);
    this.ctx = context;
    this.setData({
      videoContext: wx.createLivePlayerContext('video-livePlayer'),
    });
  },
  onLoad() {
    this.setInfo();
    this.changeviewer(1);
    this.videoVisiterRecord();
    this.isChatSupport().then((supportChat) => {
      this.setData({
        supportChat,
      });
      if (supportChat) {
        this.getLoginInfo().then(res => {
          this.joinGroup();
          this.setupLiveRoomListener();
        });
      }
    });
    this.checkDebug();
  },
  onReady: function () {
    this.createContext();
    console.log(this.data.videoContext);

    wx.setKeepScreenOn({
      keepScreenOn: true,
    });
    this.animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease',
    });
  },
  onShow: function () {
    // 保持屏幕常亮
    wx.setKeepScreenOn({
      keepScreenOn: true,
    });
    playheartbeatInterval = setInterval(() => {
      // this.checkHeartbeat();
      this.getAudienceCount();
    }, 10000);
  },
  onHide: function() {},
  onUnload: function () {
    this.stop();
    clearInterval(playheartbeatInterval);
    this.changeviewer(-1);
    wx.setKeepScreenOn({
      keepScreenOn: false,
    });
    if (this.tipInterval) {
      clearInterval(this.tipInterval);
    }
  },
  onBack: function () {
    wx.navigateBack({
      delta: 1,
    });
  },
  setInfo() {
    console.log('=================this.options', this.options);
    const { id = '', playdomain = '', playdomainHigh = '', avatar = '', anchor = '', roomTitle = '', roomid = '', groupID = '', roomBackground = '' } = this.options;
    this.setData({
      playUrl: playdomainHigh, // 默认高清
      id,
      playdomain,
      playdomainHigh,
      avatar,
      anchor,
      roomTitle,
      roomid,
      groupID,
      roomBackground,
    });
  },
  getAudienceCount() {
    app.util.request({
      url: 'entry/wxapp/index',
      data: {
        op: 'getRoomLists',
      },
      module: 'cm_lvb',
      success: (res) => {
        const list = (res.data.data && res.data.data.lists) || [];
        const room = list.find((v) => v.roomid == this.options.roomid);
        if (room) {
          this.setData({
            audienceCount: room.total,
          });
        }
      },
    });
  },
  // checkHeartbeat() {
  //   let { roomid } = this.options;
  //   app.util.request({
  //     url: 'entry/wxapp/index',
  //     data: {
  //       op: 'checkRoomLive',
  //       roomid,
  //     },
  //     module: 'cm_lvb',
  //     success: (res) => {
  //       console.log('==========play checkHeartbeat', res);
  //       if (res.data.data && res.data.data.errcode === -1) {
  //         // this.setData({
  //         //   isSucess: false,
  //         // });


  //         // wx.showModal({
  //         //   title:'系统提示',
  //         //   content: res.data.message,
  //         //   showCancel:false,
  //         //   success:res=>{
  //         //     if(res.confirm){
  //         //       this.setData({
  //         //         isSucess: false,
  //         //       });
  //         //       wx.navigateBack({});
  //         //     }
  //         //   }
  //         // })
  //       }
  //     },
          // });
  // },
  changeviewer(add=1){
    console.log('==========changeviewer add',add);
    let {
      roomid,
    } = this.options;
    app.util.request({
      url: 'entry/wxapp/index',
      data: {
        op: 'viewersChange',
        add,
        roomid,
      },
      module: 'cm_lvb',
      success: (res) => {
        console.log('==========changeviewer sucess',res);
      },
    });
  },
  onModeClick(){
    let {
      mode,
      playdomain,
      playdomainHigh,
    } = this.data;
    let playUrl = '';
    mode = mode==='SD'? 'HD':'SD';
    if(mode==='SD'){
      playUrl = playdomain;
    }else{
      playUrl = playdomainHigh;
    }
    this.setData({
      mode,
      playUrl,
    });
  },
  tohome(){
    wx.redirectTo({
      url: '../index/index',
    });
  },
  showComment() {
    getUserInfo().then(res => {
    this.setData({
      inputMsg: '',
      showComment: true,
    });
    }).catch(res => {
      app.util.navigateTo('/cm_lvb/pages/auth/auth');
    });
  },
  hideComment() {
    this.setData({
      inputMsg: '',
      showComment: false,
    });
  },
  bindInputMsg(e) {
    this.setData({
      inputMsg: e.detail.value,
    });
  },
  sendComment() {
    if (this.data.inputMsg) {
      this.sendTextMsg(this.data.inputMsg);
    }
    this.setData({
      inputMsg: '',
      showComment: false,
    });
  },
  joinGroup() {
    const groupID = this.options.groupID;
    if (groupID) {
      webimhandler.applyJoinBigGroup(groupID, ({
        errCode,
        errMsg,
        callback,
      }) => {
        if (errCode) {
          console.log('IM进群失败,', errMsg);
        } else {
          console.log('IM进群成功');
        }
      });
    }
  },
  setupLiveRoomListener() {
    liveroom.setListener({
      onRoomClose: this.onRoomClose,
      onRecvRoomTextMsg: this.onRecvRoomTextMsg,
      onRecvGroupTip: this.onRecvGroupTip,
    });
  },
  onRoomClose(e) {
    console.log('onRoomClose: e=', e);
  },
  onRecvRoomTextMsg(ret) {
    console.log('onRecvRoomTextMsg called, ret: ', ret);
    this.data.comment.unshift({
      content: ret.message,
      name: ret.userName,
      time: ret.time,
    });
    this.setData({
      comment: this.data.comment.slice(0, 8),
    }, () => {
      this.updateComment();
      },
    );
  },
  onRecvGroupTip(ret) {
    console.log('onRecvGroupTip called, ret: ', ret);
    if (ret.type === 'join') {
      this.tips.push(ret.message);
      this.showTip();
    } else {
      this.onRecvRoomTextMsg(ret);
    }
  },
  showTip() {
    if (!this.tipInterval) {
      this.showTipAnimation();
      this.tipInterval = setInterval(() => {
        this.showTipAnimation();
      }, 4000);
    }
  },
  showTipAnimation() {
    if (this.tips && this.tips.length > 0) {
      this.animation.left('-750rpx').translateX(device.windowWidth).step();
      this.setData({
        tip: this.tips.pop(),
        tipAnimation: this.animation.export(),
      }, () => {
        setTimeout(() => {
          this.animation.translateX(-device.windowWidth).step();
          this.setData({
            tipAnimation: this.animation.export(),
          });
        }, 2800);
      });
    }
  },
  wrapTextLine(text) {
    let width = 15;
    let textArray = text.split('');
    let lines = [];
    let line = '';
    for (let i = 0; i < textArray.length; i++) {
      let temp = line + textArray[i];
      if (this.ctx.measureText(temp).width + width >= 276 && i > 0) {
        lines.push(line);
        line = textArray[i];
      } else {
        line = temp;
      }
      if (i == textArray.length - 1) {
        lines.push(line);
      }
    }
    return lines;
  },
  updateComment() {
    const self = this;
    const comment = this.data.comment;
    this.ctx.clearActions();
    this.ctx.setTextBaseline('top');
    this.ctx.font = 'normal bold 14px PingFangSC';
    let y = 126;
    comment.forEach((element) => {
      self.ctx.setFillStyle('#fff');
      let text = element.name ? `${element.name}: ${element.content}` : element.content;
      let lines = self.wrapTextLine(text);
      let namePrinted = true;
      lines.forEach(function(line, index) {
        if (index === 0) {
          y += -18 * (lines.length - 1);
          if (lines[0].indexOf(':') > -1) {
            let o = lines[0].indexOf(':');
            namePrinted = true;
            self.ctx.setFillStyle('#00ECFE');
            self.ctx.fillText(lines[0].slice(0, o + 1), 0, y);
            self.ctx.setFillStyle('#FFFFFF');
            self.ctx.fillText(lines[0].slice(o + 1), self.ctx.measureText(lines[0].slice(0, o + 1)).width, y);
          } else {
            namePrinted = false;
            self.ctx.setFillStyle('#00ECFE');
            self.ctx.fillText(lines[0], 0, y);
          }
        } else {
          y -= -18;
          if (namePrinted) {
            self.ctx.setFillStyle('#FFFFFF');
            self.ctx.fillText(line, 0, y);
          } else {
            let r = line.indexOf(':');
            if (r > -1) {
              self.ctx.setFillStyle('#00ECFE');
              self.ctx.fillText(line.slice(0, r + 1), 0, y);
              self.ctx.setFillStyle('#FFFFFF');
              self.ctx.fillText(line.slice(r + 1), 0, y);
              namePrinted = true;
            } else {
              self.ctx.setFillStyle('#00ECFE');
              self.ctx.fillText(line, 0, y);
              namePrinted = false;
            }
          }
        }
      });
      y += -18 * lines.length;
    });
    this.ctx.draw(false);
  },
  sendTextMsg(text) {
    if (!this.data.isGetLoginInfo) {
      wx.showModal({
        title: '提示',
        content: '登录信息初始化中，请稍后再试',
        showCancel: false,
      });
      return;
    }
    getUserInfo().then(userInfo => {
      const nickName = userInfo.nickName;
      const avatar = userInfo.avatarUrl;
      webimhandler.sendCustomMsg({
      data: '{"cmd":"CustomTextMsg","data":{"nickName":"' + nickName + '","headPic":"' + avatar + '"}}',
      text: text,
      },
      function() {},
    );
    }).catch(res => {
      app.util.navigateTo('/cm_lvb/pages/auth/auth');
    });
  },
  toLiveList() {
    const pages = getCurrentPages();
    if (pages && pages.length > 1) {
      wx.navigateBack();
    } else {
      app.util.navigateTo('/cm_lvb/pages/index/index');
    }
  },
  videoVisiterRecord() {
    const pages = getCurrentPages();
    const route = pages[pages.length - 1].route;
    const module = route.split('/')[0];
    const roomid = this.options.roomid;

    app.util.request({
      url: 'audioVideo/audioVideo',
      data: {
        op: 'record',
        roomid,
        module,
      },
      success: (res) => {
        console.log('======videoVisiterRecord success', res);
  },
    });
  },
  onShareAppMessage() {
    const {
      roomTitle: title = '',
      playdomain = '',
      playdomainHigh = '',
      id = '',
      roomid = '',
      groupID = '',
      roomBackground:imageUrl = '',
      anchor = '',
      avatar = '',
    } = this.data;

    return {
      title,
      path: `/cm_lvb/pages/play/play?playdomain=${playdomain}&playdomainHigh=${playdomainHigh}&id=${id}&roomid=${roomid}&groupID=${groupID}&anchor=${anchor}&avatar=${avatar}&roomBackground=${imageUrl}&roomTitle=${title}`,
      imageUrl,
      success: res => {
        console.log('分享成功', res);
      },
    };
  },
  getLoginInfo() {
    return new Promise(resolve => {
      getlogininfo.getLoginInfo({
        type: 'live_room',
        success: (ret) => {
          this.setData({
            isGetLoginInfo: true,
          });
          resolve(true);
        },
        fail: (ret) => {
          this.setData({
            isGetLoginInfo: false,
          });
          resolve(false);
          wx.showModal({
            title: '提示',
            content: ret.errMsg,
            showCancel: false,
          });
        },
      });
    });
  },
});
